﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDB.Driver.Linq;
using MongoDB.Shared;
using MongoDB.Driver.Communication;



namespace KFS_Inventory_CigInput
{
    public partial class dataEntry : Form
    {
        private int currentRow;
        private int currentCell;
        private bool resetRow = false;
        string store;
        string user;
        
        List<BsonDocument> pluList = new List<BsonDocument>();

        private void UpdateName(DataGridViewRow row, List<BsonDocument> master_list)
        {
            string plu = row.Cells[0].ToString();

            foreach (BsonDocument masterEntry in master_list)
            {
                if (plu == masterEntry["PLU"].ToString())
                {
                    string quantity = row.Cells[2].ToString();
                    string[] updateRow = new string[] {plu, masterEntry["Name"].ToString(), 
                        quantity};
                    row.SetValues(updateRow);
//                    row.Cells[1].Value == masterEntry["Name"].ToString();
                }
            }
        }
        public dataEntry(string store2, string user2)
        {
            InitializeComponent();
            store = store2;
            user = user2;
            string master_table = store + "_Master";

            // Connect to the database
            var mongoConnect = "mongodb://root:b713eb8b@ds029811.mongolab.com:29811/kreiser_inventory";
            MongoClient client = new MongoClient(mongoConnect);
            MongoServer server = client.GetServer();
            MongoDatabase kfs_inv = server.GetDatabase("kreiser_inventory");
            var masterCollection = kfs_inv.GetCollection<BsonDocument>(master_table);
            var query =
                from master_entry in masterCollection.AsQueryable<BsonDocument>()
                where true
                select master_entry; // Selects every document from the db

            foreach (BsonDocument master_entry in query)
            {
                // Build a list of BsonDocuments to query later
                pluList.Add(master_entry);
            }

            //foreach (BsonDocument pluEntry in pluList)
            //{
            //    string[] row = new string[] {pluEntry["PLU"].ToString(), 
            //        pluEntry["Name"].ToString(), pluEntry["Category"].ToString()};
            //    dataGridView1.Rows.Add(row);

            //}
        }

        private void dataEntry_Load(object sender, EventArgs e)
        {

        }

        private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void doneButton_Click(object sender, EventArgs e)
        {
            // Done code here
            int counter = 0;
            var mongoConnect = "mongodb://root:b713eb8b@ds029811.mongolab.com:29811/kreiser_inventory";
            MongoClient client = new MongoClient(mongoConnect);
            MongoServer server = client.GetServer();
            MongoDatabase kfs_inv = server.GetDatabase("kreiser_inventory");
            var cigCollection = kfs_inv.GetCollection<BsonDocument>(store + "_Cigs");
//            var batch = new 
            var batch = cigCollection.InitializeUnorderedBulkOperation();
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                string plu = Convert.ToString(row.Cells[0].Value); // Get PLU from datagridview
                int quantity = Convert.ToInt32(row.Cells[2].Value); // Get quantity from datagridview
                if (plu != "")
                {
                    BsonDocument writeEntry = new BsonDocument {
                    {"PLU", plu},
                    {"Quantity", quantity},
                    {"User", user},
                    {"date", DateTime.Now}}; // Must write these docs to an array and batch insert.
                    batch.Insert<BsonDocument>(writeEntry); // Insert the new entry to the bulk operation
                    counter++;
                }


            }
            batch.Execute(); // Writes the batch to the db
            MessageBox.Show("You have entered " + counter.ToString() + " entries into the database.");
            this.Close();

        }

        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            int rowIndex = e.RowIndex;
            int colIndex = e.ColumnIndex;
            if (colIndex == 0 && rowIndex >= 0) // A PLU was added
            {
                string addedPLU = dataGridView1.Rows[rowIndex].Cells["PLU"].Value.ToString();
                foreach (BsonDocument masterEntry in pluList) // Add the name of the entered PLU to col[1]
                {
                    if (masterEntry["PLU"].ToString() == addedPLU)
                    {
                        string addedName = masterEntry["Name"].ToString();
                        dataGridView1.Rows[rowIndex].Cells["pluName"].Value = addedName;
                        break;
                    }
                }
            }
        }

        private void dataGridView1_NewRowNeeded(object sender, DataGridViewRowEventArgs e)
        {
            
        }

        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e)
        {


        }

        private void dataGridView1_KeyUp(object sender, KeyEventArgs e)
        {

        }

        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            if (resetRow)
            {
                resetRow = false;
                if ((Int32)dataGridView1.CurrentCell.ColumnIndex != dataGridView1.Columns.Count - 1)
                    dataGridView1.CurrentCell = dataGridView1.Rows[currentRow].Cells[currentCell + 2];
                else
                    dataGridView1.CurrentCell = dataGridView1.Rows[currentRow + 1].Cells[0];
            }
        }

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            resetRow = true;
            currentRow = e.RowIndex;
            currentCell = e.ColumnIndex; // Gets the column and row when an edit ends
        }

        private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            dataGridView1.Rows[e.RowIndex].ErrorText = "";
            if (e.ColumnIndex == 2) // Quantity must be positive integer
            {
                int newInteger;
                if (dataGridView1.Rows[e.RowIndex].IsNewRow)
                {
                    return;
                }
                if (!int.TryParse(e.FormattedValue.ToString(),
                    out newInteger) || newInteger < 0)
                {
                    e.Cancel = true;
                    dataGridView1.Rows[e.RowIndex].ErrorText = "Quantity must be a positive whole number.";
                }
            }
            if (e.ColumnIndex == 0) // PLU must be in pluList and department 1, 2, or 19
            {
                if (dataGridView1.Rows[e.RowIndex].IsNewRow)
                {
                    return; // If the row isn't complete yet, don't do anything
                }
                else
                {
                    int foundMatch = 0;
                    foreach (BsonDocument master_entry in pluList)
                    {
                        string addedPLU = master_entry["PLU"].ToString();
                        string addedDep = master_entry["Category"].ToString();
                        if (addedPLU == e.FormattedValue.ToString() && (addedDep == "1" ||
                                        addedDep == "2" || addedDep == "19"))
                        {
                            foundMatch = 1;
                            break;
                        }
                    }
                    if (foundMatch == 0) // The entered PLU is not in 1, 2, or 19, or is not in the db
                    {
                        e.Cancel = true;
                        dataGridView1.Rows[e.RowIndex].ErrorText =
                                "The PLU entered does not match our records.";
                    }
                }
            }

        }
    }
}
